package muxwstemplate

import (
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

var clientGroupManager = &ClientGroupManager{
	ClientGroups: make(map[string]map[*websocket.Conn]bool),
}

func GetClientGroupManager() *ClientGroupManager {
	return clientGroupManager
}

func UpgradeToWebSocket(w http.ResponseWriter, r *http.Request, groupName string, whenMsgArrived func([]byte) []byte) {

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		muxWSLogger.Errorf("WebSocket upgrade fail: %v", err)
		return
	}
	defer conn.Close()
	muxWSLogger.Infof("New connection has been add to the group[%s]", groupName)

	// 添加连接到房间
	clientGroupManager.AddClientToGroup(groupName, conn)
	defer clientGroupManager.RemoveClientFromGroup(groupName, conn)

	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			muxWSLogger.Errorf("Failed to read data from connection : %v", err)
			break
		}

		muxWSLogger.Infof("Recive data from connection , group : %s , msg : %s", groupName, message)
		result := whenMsgArrived(message)

		// 回传消息给客户端
		if messageType == websocket.TextMessage {
			conn.WriteMessage(websocket.TextMessage, result)
		}
	}
}
